// app/controller/api/wechatPay.js

'use strict';

const xml2js = require('xml2js').parseString;
const Controller = require('egg').Controller;

class WechatPayController extends Controller {

    // 微信支付
    async wxpay() {
        const { ctx, app, service } = this;
        let user_id = ctx.authUser.id

        ctx.validate({
            price: {
                type: "int",
                required: true,
                desc: "充值费用"
            }
        })

        let { price } = ctx.request.body
        price = parseInt(price)
        if (price < 1) {
            return ctx.apiFail('至少充值1元')
        }

        // 创建订单
        let no = ctx.randomString(32)
        let openid = await this.ctx.authUser.openid;
        let order = await app.model.Order.create({
            no,
            user_id,
            price
        })

        if (!order) {
            return ctx.apiFail('创建订单失败')
        }
        let data = {
            out_trade_no: no,
            body: '充值',
            total_fee: price
        }
        // 支付
        let result = await service.mp.createOrder(openid, data)

        ctx.apiSuccess(result)
    }

    // 支付回调
    async notify() {
        const { ctx, app, service } = this;
    const xmlData = ctx.request.body;
    let data = await service.mp.notify(xmlData)
    console.log(data)

        // 查询当前订单
        let order = await app.model.Order.findOne({
            where: {
                no: data.out_trade_no
            }
        })
        console.log(order)

        if (!order) {
            return ctx.apiFail('订单不存在')
        }

        // 修改订单状态
        order.status = 'success'
        order.save()

        // 修改用户余额
        let user = await service.user.exist(order.user_id)
        if (user) {
            user.coin += data.total_fee / 100
            user.save()
        }

        return {
            code:"SUCCESS",
            message:""
        }
    }
}

module.exports = WechatPayController;